import { useState, useRef, useEffect, useContext } from 'react';
import { SearchBar, Grid, List, InfiniteScroll } from "antd-mobile";
import { FolderOutline, PictureOutline, LinkOutline } from 'antd-mobile-icons';
import { useHistory, useRouteMatch } from 'react-router-dom';
import xss from 'xss';
import moment from 'moment';

import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { cid } } = useRouteMatch();
  const [result, setResult] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 1 });
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.nativeElement.focus();
  }, [])

  // 处理搜索框点击”取消“事件，搜索框有值则清空搜索框，无值则返回上一页
  const handleCancel = () => {
    if (result.length) {
      setResult([]);
      setPagination({ pageIndex: 1 });
    } else {
      history.goBack();
    }
  }

  // 处理”搜索“事件
  const handleSearch = async (value: string, pageIndex = 1) => {
    if (!value) {
      return;
    }
    const { rows, current, totalItemCount, totalPage } = await mySdkStore.sdk.searchMessage({ searchKey: value, pageIndex, sessionIds: [cid] });
    setResult(pageIndex === 1 ? rows : [...result, ...rows]);
    setPagination({ pageIndex: current, totalItemCount, totalPage, searchKey: value });
  }

  // 获取分页数据
  const getNextData = async () => {
    await handleSearch(pagination.searchKey, pagination.pageIndex + 1);
  }

  return (
    <div className="searchMessageContentPage">
      <div className="searchBar">
        <SearchBar ref={inputRef} placeholder='搜索' className="searchInput" style={{ '--background': '#fff' }} showCancelButton onSearch={handleSearch} onCancel={handleCancel} />
      </div>
      { !result.length && !pagination.searchKey ? <div className="filterArea">
        <div className="tip">快速搜索关键词</div>
        <Grid columns={3}>
          <Grid.Item onClick={() => history.push({ pathname: `/searchMessageFile/${cid}` })}>
            <div className="iconBox">
              <FolderOutline style={{ fontSize: 22 }} />
            </div>
            文件
          </Grid.Item>
          <Grid.Item onClick={() => history.push({ pathname: `/searchMessagePicture/${cid}` })}>
            <div className="iconBox">
              <PictureOutline style={{ fontSize: 22 }}  />
            </div>
            图片&视频
          </Grid.Item>
          <Grid.Item onClick={() => history.push({ pathname: `/searchMessageLink/${cid}` })}>
            <div className="iconBox">
              <LinkOutline style={{ fontSize: 22 }}  />
            </div>
            链接
          </Grid.Item>
        </Grid>
      </div>
      :
      <div className="result">
        <List>
          { result.map((item) => <List.Item
            key={List.msgId}
            prefix={<AvatarImage style={{ borderRadius: '8'}} src={item.from?.avatarUrl}
            nickName={item.from?.nickName}
            userName={item.from?.userName}
            userId={item.from?.userId}
            width={42} height={42} fit='fill' />}
            description={<div className="searchContent" dangerouslySetInnerHTML={{__html: xss(item.searchContent)}}></div>}
          >
            <div className="userinfoBar">
              {/* todo: 缺少to字段 */}
              {/* { item.from.userId } &gt; { item.to } */}
              { item.from.nickName }
              <span className="time">{ moment(item.timestamp).format('HH:mm') }</span>
            </div>
          </List.Item>)}
        </List>
        <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
      </div>
      }
    </div>)
}